package chapter12.eg2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;

public class NettyServer {

  public void bind(int port) throws InterruptedException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class)
      .option(ChannelOption.SO_BACKLOG, 1024)
      .handler(new LoggingHandler(LogLevel.INFO))
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ch.pipeline().addLast(new NettyMessageDecoder());
          ch.pipeline().addLast(new NettyMessageEncoder());
          ch.pipeline().addLast("ReadTimeoutHandler", new ReadTimeoutHandler(50));
          ch.pipeline().addLast(new LoginAuthRespHandler());
          ch.pipeline().addLast("HeartBeatHandler", new HeartBeatRespHandler());
        }
      });

    bootstrap.bind(port).sync();
    System.out.println("Netty Server start ok! ");
  }

  public static void main(String[] args) throws InterruptedException {
    new NettyServer().bind(8080);
  }

}
